package com.kiln.juxingqs.ui.vm

import android.app.Application
import android.graphics.Bitmap
import android.text.TextUtils
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import client.global.commlib.network.data.JsonResult
import client.global.commlib.network.data.Ret
import client.global.commlib.out_time
import client.global.commlib.toast.toast
import client.global.commlib.utils.Util
import com.kiln.juxingqs.api.bean.PayAccount
import com.kiln.juxingqs.api.bean.PayAccount2
import com.kiln.juxingqs.api.bean.UploadRet
import com.kiln.juxingqs.ui.viewmodel.MiddleVm
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import retrofit2.Response

class SetskxxNewViewModel(app: Application) : MiddleVm(app) {
    val isShowing = MutableLiveData<Boolean>(false)
    val bankName = MutableLiveData<String>()//银行名称
    val phone = MutableLiveData<String>()
    val smscodeThree = MutableLiveData<String>()


    val realName = MutableLiveData<String>()//收款姓名
    val idcard = MutableLiveData<String>()//收款姓名
    val userAddr = MutableLiveData<String>()//身份证有效期
    val userEmail = MutableLiveData<String>()//身份证有效期
    val qu = MutableLiveData<String>("")
    val quIds = MutableLiveData<String>("")

    val quBank = MutableLiveData<String>("")
    val quIdsBank = MutableLiveData<String>("")

    val bankCard = MutableLiveData<String>()
    val getCodeTxt = MutableLiveData<String>("获取验证码")
    val getCodeEnable = MutableLiveData<Boolean>(true)
    val callThree = MutableLiveData<JsonResult<Ret>>()
    val callEditBank = MutableLiveData<JsonResult<Ret>>()
    val codeRet = MutableLiveData<JsonResult<Ret>>()
    val dataThree = MutableLiveData<JsonResult<PayAccount2>>()

    val idcardFont = MutableLiveData<Bitmap>(null)
    val idcardBack = MutableLiveData<Bitmap>(null)
    val idcardFontHand = MutableLiveData<Bitmap>(null)
    val bankcardFont = MutableLiveData<Bitmap>(null)
    val bandcardBack = MutableLiveData<Bitmap>(null)
    val bandcardHand = MutableLiveData<Bitmap>(null)


    val idcardFontUrl = MutableLiveData<String>(null)
    val idcardBackUrl = MutableLiveData<String>(null)
    val idcardFontHandUrl = MutableLiveData<String>(null)
    val bankcardFontUrl = MutableLiveData<String>(null)
    val bandcardBackUrl = MutableLiveData<String>(null)
    val bandcardHandUrl = MutableLiveData<String>(null)
    val bandcardHand2Url = MutableLiveData<String>(null)

    val applyNo = MutableLiveData<String>(null)

    val id_card_type = MutableLiveData<String>("1")  //身份证有效期 1有效期 2永久有效

    val startDate = MutableLiveData<String>("")
    val endDate = MutableLiveData<String>("")


    fun swichSta(i: Int) {

        when (i) {

            0 -> {
                id_card_type.value = "1"
            }

            else -> {
                id_card_type.value = "2"
            }
        }

    }

    fun callThree() {
        hold({

            server.user_pay_account2()
        }, success = {
            dataThree.value = it
        })
    }

    fun getCode() {

        if (TextUtils.isEmpty(phone.value)) {
            toast("手机号不能为空")
            return
        }

        isShowing.value = true
        hold({
            val ts = System.currentTimeMillis()
            server.getcode(
                phone.value!!,
                "${ts}",
                Util.getCaptchaSign(phone.value!!, "${ts}")
            )
        }, {
            getCodeEnable.value = false
        }, {
            codeRet.value = it
        }, complete = {
            isShowing.value = false
        }, err = {
            getCodeEnable.value = true
        })

    }


    fun ok(owner: LifecycleOwner) {

        isShowing.value = true
        viewModelScope.launch {
            flow {
                var emm: JsonResult<UploadRet>? = null
                if (!bankcardFontUrl.value.isNullOrEmpty()) {
                    emm = JsonResult<UploadRet>().apply {
                        data = UploadRet("", bankcardFontUrl.value!!)
                        code = 200
                    }
                } else {
                    val file = Util.getLuBan(
                        owner,
                        bankcardFont.value!!
                    )
                    val requestFile: RequestBody = RequestBody.create(
                        "multipart/form-data".toMediaTypeOrNull(),
                        file
                    )
                    val body = MultipartBody.Part.createFormData(
                        "file",
                        file.name,
                        requestFile
                    )
                    val descriptionString = "12"
                    val description = RequestBody.create(
                        "multipart/form-data".toMediaTypeOrNull(),
                        descriptionString
                    )
                    out_time {
                        val ret = server.hfb_upload_img(description, body)
                        emm = ret.body()
                    }
                }
                emit(emm)
            }.map {
                var emm: JsonResult<UploadRet>? = null
                it?.let {
                    if (it.isSuccess) {

                        withContext(Dispatchers.Main) {
                            bankcardFontUrl.value = it.data?.url_path
                        }

                        if (!bandcardBackUrl.value.isNullOrEmpty()) {
                            emm = JsonResult<UploadRet>().apply {
                                data = UploadRet("", bandcardBackUrl.value!!)
                                code = 200
                            }
                        } else {
                            out_time {

                                val file = Util.getLuBan(
                                    owner,
                                    bandcardBack.value!!
                                )
                                val requestFile: RequestBody = RequestBody.create(
                                    "multipart/form-data".toMediaTypeOrNull(),
                                    file
                                )
                                val body = MultipartBody.Part.createFormData(
                                    "file",
                                    file.name,
                                    requestFile
                                )

                                val descriptionString = "13"
                                val description = RequestBody.create(
                                    "multipart/form-data".toMediaTypeOrNull(),
                                    descriptionString
                                )
                                out_time {
                                    val ret = server.hfb_upload_img(description, body)
                                    emm = ret.body()
                                }

                            }
                        }

                    }
                }
                emm
            }.map {
                var emm: JsonResult<UploadRet>? = null
                it?.let {
                    if (it.isSuccess) {

                        withContext(Dispatchers.Main) {
                            bandcardBackUrl.value = it.data?.url_path
                        }
                        if (!bandcardHandUrl.value.isNullOrEmpty()) {
                            emm = JsonResult<UploadRet>().apply {
                                data = UploadRet("", bandcardHandUrl.value!!)
                                code = 200
                            }
                        } else {
                            out_time {

                                val file = Util.getLuBan(
                                    owner,
                                    bandcardHand.value!!
                                )
                                val requestFile: RequestBody = RequestBody.create(
                                    "multipart/form-data".toMediaTypeOrNull(),
                                    file
                                )
                                val body = MultipartBody.Part.createFormData(
                                    "file",
                                    file.name,
                                    requestFile
                                )
                                val descriptionString = "14"
                                val description = RequestBody.create(
                                    "multipart/form-data".toMediaTypeOrNull(),
                                    descriptionString
                                )
                                out_time {
                                    val ret = server.hfb_upload_img(description, body)
                                    emm = ret.body()
                                }

                            }
                        }
                    }
                }
                emm
            }.map {
                var emm: JsonResult<UploadRet>? = null
                it?.let {
                    if (it.isSuccess) {

                        withContext(Dispatchers.Main) {
                            bandcardHandUrl.value = it.data?.url_path
                        }
                        if (!idcardFontUrl.value.isNullOrEmpty()) {
                            emm = JsonResult<UploadRet>().apply {
                                data = UploadRet("", idcardFontUrl.value!!)
                                code = 200
                            }
                        } else {

                            out_time {

                                val file = Util.getLuBan(
                                    owner,
                                    idcardFont.value!!
                                )
                                val requestFile: RequestBody = RequestBody.create(
                                    "multipart/form-data".toMediaTypeOrNull(),
                                    file
                                )
                                val body = MultipartBody.Part.createFormData(
                                    "file",
                                    file.name,
                                    requestFile
                                )
                                val descriptionString = "15"
                                val description = RequestBody.create(
                                    "multipart/form-data".toMediaTypeOrNull(),
                                    descriptionString
                                )
                                out_time {
                                    val ret = server.hfb_upload_img(description, body)
                                    emm = ret.body()
                                }

                            }
                        }
                    }
                }
                emm
            }.map {
                var emm: JsonResult<UploadRet>? = null
                it?.let {
                    if (it.isSuccess) {
                        withContext(Dispatchers.Main) {
                            idcardFontUrl.value = it.data?.url_path
                        }
                        if (!idcardBackUrl.value.isNullOrEmpty()) {
                            emm = JsonResult<UploadRet>().apply {
                                data = UploadRet("", idcardBackUrl.value!!)
                                code = 200
                            }
                        } else {
                            out_time {

                                val file = Util.getLuBan(
                                    owner,
                                    idcardBack.value!!
                                )
                                val requestFile: RequestBody = RequestBody.create(
                                    "multipart/form-data".toMediaTypeOrNull(),
                                    file
                                )
                                val body = MultipartBody.Part.createFormData(
                                    "file",
                                    file.name,
                                    requestFile
                                )
                                val descriptionString = "16"
                                val description = RequestBody.create(
                                    "multipart/form-data".toMediaTypeOrNull(),
                                    descriptionString
                                )
                                out_time {
                                    val ret = server.hfb_upload_img(description, body)
                                    emm = ret.body()
                                }

                            }
                        }
                    }
                }
                emm
            }.map {
                var emm: JsonResult<UploadRet>? = null
                it?.let {
                    if (it.isSuccess) {

                        withContext(Dispatchers.Main) {
                            idcardBackUrl.value = it.data?.url_path
                        }
                        if (!idcardFontHandUrl.value.isNullOrEmpty()) {
                            emm = JsonResult<UploadRet>().apply {
                                data = UploadRet("", idcardFontHandUrl.value!!)
                                code = 200
                            }
                        } else {
                            out_time {

                                val file = Util.getLuBan(
                                    owner,
                                    idcardFontHand.value!!
                                )
                                val requestFile: RequestBody = RequestBody.create(
                                    "multipart/form-data".toMediaTypeOrNull(),
                                    file
                                )
                                val body = MultipartBody.Part.createFormData(
                                    "file",
                                    file.name,
                                    requestFile
                                )
                                val descriptionString = "17"
                                val description = RequestBody.create(
                                    "multipart/form-data".toMediaTypeOrNull(),
                                    descriptionString
                                )
                                out_time {
                                    val ret = server.hfb_upload_img(description, body)
                                    emm = ret.body()
                                }

                            }
                        }
                    }
                }
                emm
            }.map {
                var emm: JsonResult<UploadRet>? = null
                it?.let {
                    if (it.isSuccess) {
                        withContext(Dispatchers.Main) {
                            idcardFontHandUrl.value = it.data?.url_path
                        }
                        if (!bandcardHand2Url.value.isNullOrEmpty()) {
                            emm = JsonResult<UploadRet>().apply {
                                data = UploadRet("", bandcardHand2Url.value!!)
                                code = 200
                            }
                        } else {
                            out_time {

                                val file = Util.getLuBan(
                                    owner,
                                    bandcardHand.value!!
                                )
                                val requestFile: RequestBody = RequestBody.create(
                                    "multipart/form-data".toMediaTypeOrNull(),
                                    file
                                )
                                val body = MultipartBody.Part.createFormData(
                                    "file",
                                    file.name,
                                    requestFile
                                )
                                val descriptionString = "18"
                                val description = RequestBody.create(
                                    "multipart/form-data".toMediaTypeOrNull(),
                                    descriptionString
                                )
                                out_time {
                                    val ret = server.hfb_upload_img(description, body)
                                    emm = ret.body()
                                }

                            }
                        }
                    }
                }
                emm
            }.map {
                var emm: JsonResult<Ret>? = null
                it?.let {
                    if (it.isSuccess) {
                        withContext(Dispatchers.Main) {
                            bandcardHand2Url.value = it.data?.url_path
                        }
                        out_time {

                            var quCOde = ""
                            quIds.value!!.split(" ")?.let {
                                if (it.size == 3)
                                    quCOde = it[2]
                            }
                            var quCOdeBank = ""
                            quIdsBank.value!!.split(" ")?.let {
                                if (it.size == 3)
                                    quCOdeBank = it[2]
                            }

                            val ret = server.createUser(
                                realName.value,
                                idcard.value,
                                id_card_type.value,
                                startDate.value,
                                endDate.value,
                                phone.value,
                                quCOde,
                                userAddr.value,
                                userEmail.value,
                                bankCard.value,
                                bankName.value,
                                quCOdeBank,
                                bankcardFontUrl.value,
                                bandcardBackUrl.value,
                                bandcardHandUrl.value,
                                idcardFontUrl.value,
                                idcardBackUrl.value,
                                idcardFontHandUrl.value,
                                bandcardHand2Url.value
                            )
                            emm = ret.body()
                        }
                    }
                }
                emm
            }.flowOn(Dispatchers.IO).onCompletion { cause ->
                isShowing.value = false
            }.catch { cause ->
                if (cause != null) {
                    toast(cause.message)
                }
            }
                .collectLatest {
                    callThree.value = it
                }
        }
    }


    fun okEditBank(owner: LifecycleOwner) {

        isShowing.value = true
        viewModelScope.launch {
            flow {
                var emm: JsonResult<UploadRet>? = null

                if (!bankcardFontUrl.value.isNullOrEmpty()) {
                    emm = JsonResult<UploadRet>().apply {
                        data = UploadRet("", bankcardFontUrl.value!!)
                        code = 200
                    }
                } else {
                    val file = Util.getLuBan(
                        owner,
                        bankcardFont.value!!
                    )
                    val requestFile: RequestBody = RequestBody.create(
                        "multipart/form-data".toMediaTypeOrNull(),
                        file
                    )
                    val body = MultipartBody.Part.createFormData(
                        "file",
                        file.name,
                        requestFile
                    )
                    val descriptionString = "12"
                    val description = RequestBody.create(
                        "multipart/form-data".toMediaTypeOrNull(),
                        descriptionString
                    )
                    out_time {
                        val ret = server.hfb_upload_img(description, body)
                        emm = ret.body()
                    }
                }
                emit(emm)
            }.map {
                var emm: JsonResult<UploadRet>? = null
                it?.let {
                    if (it.isSuccess) {

                        withContext(Dispatchers.Main) {
                            bankcardFontUrl.value = it.data?.url_path
                        }

                        if (!bandcardBackUrl.value.isNullOrEmpty()) {
                            emm = JsonResult<UploadRet>().apply {
                                data = UploadRet("", bandcardBackUrl.value!!)
                                code = 200
                            }
                        } else {
                            out_time {

                                val file = Util.getLuBan(
                                    owner,
                                    bandcardBack.value!!
                                )
                                val requestFile: RequestBody = RequestBody.create(
                                    "multipart/form-data".toMediaTypeOrNull(),
                                    file
                                )
                                val body = MultipartBody.Part.createFormData(
                                    "file",
                                    file.name,
                                    requestFile
                                )

                                val descriptionString = "13"
                                val description = RequestBody.create(
                                    "multipart/form-data".toMediaTypeOrNull(),
                                    descriptionString
                                )
                                out_time {
                                    val ret = server.hfb_upload_img(description, body)
                                    emm = ret.body()
                                }

                            }
                        }
                    }
                }
                emm
            }.map {
                var emm: JsonResult<UploadRet>? = null
                it?.let {
                    if (it.isSuccess) {

                        withContext(Dispatchers.Main) {
                            bandcardBackUrl.value = it.data?.url_path
                        }
                        if (!bandcardHandUrl.value.isNullOrEmpty()) {
                            emm = JsonResult<UploadRet>().apply {
                                data = UploadRet("", bandcardHandUrl.value!!)
                                code = 200
                            }
                        } else {

                            out_time {

                                val file = Util.getLuBan(
                                    owner,
                                    bandcardHand.value!!
                                )
                                val requestFile: RequestBody = RequestBody.create(
                                    "multipart/form-data".toMediaTypeOrNull(),
                                    file
                                )
                                val body = MultipartBody.Part.createFormData(
                                    "file",
                                    file.name,
                                    requestFile
                                )
                                val descriptionString = "14"
                                val description = RequestBody.create(
                                    "multipart/form-data".toMediaTypeOrNull(),
                                    descriptionString
                                )
                                out_time {
                                    val ret = server.hfb_upload_img(description, body)
                                    emm = ret.body()
                                }

                            }
                        }
                    }
                }
                emm
            }.map {
                var emm: JsonResult<Ret>? = null
                it?.let {
                    if (it.isSuccess) {
                        withContext(Dispatchers.Main) {
                            bandcardHandUrl.value = it.data?.url_path
                        }
                        out_time {

                            var quCOde = ""
                            quIds.value!!.split(" ")?.let {
                                if (it.size == 3)
                                    quCOde = it[2]
                            }
                            var quCOdeBank = ""
                            quIdsBank.value!!.split(" ")?.let {
                                if (it.size == 3)
                                    quCOdeBank = it[2]
                            }

                            val ret = server.editBank(
                                bankCard.value,
                                bankName.value,
                                quCOdeBank,
                                bankcardFontUrl.value,
                                bandcardBackUrl.value,
                                bandcardHandUrl.value,
                                applyNo.value,
                            )
                            emm = ret.body()
                        }
                    }
                }
                emm
            }.flowOn(Dispatchers.IO).onCompletion { cause ->
                isShowing.value = false
            }.catch { cause ->
                if (cause != null) {
                    toast(cause.message)
                }
            }
                .collectLatest {
                    callEditBank.value = it
                }
        }
    }

}